"""
错误处理模块
"""
from flask import jsonify
from typing import Tuple


class StockAnalyzerError(Exception):
    """股票分析器基础异常类"""

    def __init__(self, message: str, error_code: str = None, status_code: int = 500):
        super().__init__(message)
        self.message = message
        self.error_code = error_code or "INTERNAL_ERROR"
        self.status_code = status_code


class DataFetchError(StockAnalyzerError):
    """数据获取错误"""

    def __init__(self, message: str, symbol: str = None):
        super().__init__(message, "DATA_FETCH_ERROR", 500)
        self.symbol = symbol


class RateLimitError(StockAnalyzerError):
    """API限流错误"""

    def __init__(self, message: str, retry_after: str = "a few minutes"):
        super().__init__(message, "RATE_LIMIT_EXCEEDED", 429)
        self.retry_after = retry_after


class AIServiceError(StockAnalyzerError):
    """AI服务错误"""

    def __init__(self, message: str):
        super().__init__(message, "AI_SERVICE_ERROR", 500)


class ValidationError(StockAnalyzerError):
    """数据验证错误"""

    def __init__(self, message: str):
        super().__init__(message, "VALIDATION_ERROR", 400)


class APIKeyMissingError(StockAnalyzerError):
    """API密钥缺失错误"""

    def __init__(self, message: str = "API key is missing"):
        super().__init__(message, "API_KEY_MISSING", 500)


def handle_stock_data_error(error: Exception, symbol: str = None) -> Tuple[dict, int]:
    """
    处理股票数据相关错误

    Args:
        error: 异常对象
        symbol: 股票代码

    Returns:
        (错误响应, 状态码) 元组
    """
    error_msg = str(error)
    print(f"Error in stock data operation: {error_msg}")

    # 检查是否为429错误
    if "429" in error_msg:
        return jsonify({
            'error': 'API rate limit exceeded',
            'details': 'Yahoo Finance API is temporarily unavailable due to too many requests. Please try again in a few minutes.',
            'error_code': 'RATE_LIMIT_EXCEEDED',
            'retry_after': 'a few minutes'
        }), 429
    else:
        return jsonify({
            'error': 'Failed to fetch stock data',
            'details': error_msg,
            'symbol': symbol
        }), 500


def handle_financial_data_error(error: Exception, symbol: str = None) -> Tuple[dict, int]:
    """
    处理财务数据相关错误

    Args:
        error: 异常对象
        symbol: 股票代码

    Returns:
        (错误响应, 状态码) 元组
    """
    error_msg = str(error)
    print(f"Error in financial data operation: {error_msg}")

    if "429" in error_msg:
        return jsonify({
            'error': 'API rate limit exceeded',
            'details': 'Yahoo Finance API is temporarily unavailable due to too many requests. Please try again in a few minutes.',
            'error_code': 'RATE_LIMIT_EXCEEDED',
            'retry_after': 'a few minutes'
        }), 429
    else:
        return jsonify({
            'error': 'Failed to fetch financial data',
            'details': error_msg,
            'symbol': symbol
        }), 500


def handle_risk_analysis_error(error: Exception, symbol: str = None) -> Tuple[dict, int]:
    """
    处理风险分析相关错误

    Args:
        error: 异常对象
        symbol: 股票代码

    Returns:
        (错误响应, 状态码) 元组
    """
    error_msg = str(error)
    print(f"Error in risk analysis: {error_msg}")

    if "429" in error_msg:
        return jsonify({
            'error': 'API rate limit exceeded',
            'details': 'Yahoo Finance API is temporarily unavailable due to too many requests. Please try again in a few minutes.',
            'error_code': 'RATE_LIMIT_EXCEEDED',
            'retry_after': 'a few minutes'
        }), 429
    else:
        return jsonify({
            'error': 'Failed to calculate risk metrics',
            'details': error_msg,
            'symbol': symbol
        }), 500


def handle_ai_analysis_error(error: Exception, symbol: str = None) -> Tuple[dict, int]:
    """
    处理AI分析相关错误

    Args:
        error: 异常对象
        symbol: 股票代码

    Returns:
        (错误响应, 状态码) 元组
    """
    error_msg = str(error)
    print(f"Error in AI analysis: {error_msg}")

    # 检查是否有error_code属性（自定义异常）
    if hasattr(error, 'error_code'):
        return jsonify({
            'error': error_msg,
            'details': error_msg,
            'error_code': error.error_code,
            'symbol': symbol
        }), 500

    # 检查是否为429错误
    if "429" in error_msg:
        return jsonify({
            'error': 'API rate limit exceeded',
            'details': 'Yahoo Finance API is temporarily unavailable due to too many requests. Please try again in a few minutes.',
            'error_code': 'RATE_LIMIT_EXCEEDED',
            'retry_after': 'a few minutes',
            'symbol': symbol
        }), 429
    else:
        return jsonify({
            'error': 'Failed to generate AI analysis',
            'details': error_msg,
            'error_code': 'AI_ANALYSIS_ERROR',
            'symbol': symbol
        }), 500


def handle_stream_error(error: Exception) -> str:
    """
    处理流式响应错误

    Args:
        error: 异常对象

    Returns:
        JSON格式的错误消息字符串
    """
    import json
    error_msg = str(error)
    print(f"Error in streaming response: {error_msg}")

    return json.dumps({'error': f'Streaming error: {error_msg}'})


def handle_investment_recommendation_error(error: Exception, symbol: str = None) -> Tuple[dict, int]:
    """
    处理投资建议相关错误

    Args:
        error: 异常对象
        symbol: 股票代码

    Returns:
        (错误响应, 状态码) 元组
    """
    error_msg = str(error)
    print(f"Error in investment recommendation: {error_msg}")

    if "429" in error_msg:
        return jsonify({
            'error': 'API rate limit exceeded',
            'details': 'Yahoo Finance API is temporarily unavailable due to too many requests. Please try again in a few minutes.',
            'error_code': 'RATE_LIMIT_EXCEEDED',
            'retry_after': 'a few minutes'
        }), 429
    else:
        return jsonify({
            'error': 'Failed to generate investment recommendation',
            'details': error_msg,
            'symbol': symbol
        }), 500


def handle_chart_data_error(error: Exception, symbol: str = None) -> Tuple[dict, int]:
    """
    处理图表数据相关错误

    Args:
        error: 异常对象
        symbol: 股票代码

    Returns:
        (错误响应, 状态码) 元组
    """
    error_msg = str(error)
    print(f"Error in chart data: {error_msg}")

    return jsonify({
        'error': 'Failed to fetch chart data',
        'details': error_msg,
        'symbol': symbol
    }), 500